/**
 * Created by zhangyuanying on 17/11/.
 */

var dateUtil = {

  // 对Date的扩展，将 Date 转化为指定格式的String
  // 月(M)、日(d)、小时(h)、分(m)、秒(s)、季度(q) 可以用 1-2 个占位符，
  // 年(y)可以用 1-4 个占位符，毫秒(S)只能用 1 个占位符(是 1-3 位的数字)
  // 例子：
  // (new Date()).Format("yyyy-MM-dd hh:mm:ss.S") ==> 2006-07-02 08:09:04.423
  // (new Date()).Format("yyyy-M-d h:m:s.S")      ==> 2006-7-2 8:9:4.18
  format: function (ns, format) {
    if (!ns) {
      return '';
    }
    var dateObj = new Date(parseInt(ns));
    var date = {
      "M+": dateObj.getMonth() + 1,
      "d+": dateObj.getDate(),
      "h+": dateObj.getHours(),
      "m+": dateObj.getMinutes(),
      "s+": dateObj.getSeconds(),
      "q+": Math.floor((dateObj.getMonth() + 3) / 3),
      "S+": dateObj.getMilliseconds()
    };
    if (/(y+)/i.test(format)) {
      format = format.replace(RegExp.$1, (dateObj.getFullYear() + '').substr(4 - RegExp.$1.length));
    }
    for (var k in date) {
      if (new RegExp("(" + k + ")").test(format)) {
        format = format.replace(RegExp.$1, RegExp.$1.length == 1 ? date[k] : ("00" + date[k]).substr(("" + date[k]).length));
      }
    }
    return format;
  },
  onlyYear: function (ns) {
    if (ns) {
      return this.format(ns, 'yyyy');
    }
    return ns || '';
  },
  yearAndMonthFormat: function (ns) {
    if (ns) {
      return this.format(ns, 'yyyy-MM');
    }
    return ns || '';
  },
  dateFormat: function (ns) {
    if (ns) {
      return this.format(ns, 'yyyy-MM-dd');
    }
    return ns || '';
  },
  datePointFormat: function (ns) {
    if (ns) {
      return this.format(ns, 'yyyy.MM.dd');
    }
    return ns || '';
  },
  dateTimeFormat: function (ns) {
    if (ns) {
      return this.format(ns, 'yyyy-MM-dd hh:mm');
    }
    return ns || '';
  },
  dateSTimeFormat: function (ns) {
    if (ns) {
      return this.format(ns, 'yyyy-MM-dd hh:mm:ss');
    }
    return ns || '';
  },
  dateMonthFormat: function (ns) {
    if (ns) {
      return this.format(ns, 'MM.dd');
    }
    return ns || '';
  },
  friendly: function (ns, isDiff) {
    var diff;
    if (isDiff) {
      diff = ns;
    } else {
      var now = Date.now(), date = new Date(ns);
      diff = now - date;
    }
    var day = Math.floor(diff / 86400000);
    if (day > 0) {
      return day + '天';
    }
    var hour = Math.floor(diff % 86400000 / 3600000);
    if (hour > 0) {
      return hour + "小时";
    }
    var min = Math.floor(diff % 86400000 % 3600000 / 60000);
    if (min > 0) {
      return min + '分钟';
    }
    return '刚刚';
  },
  getTimeByDiff(diff) {
    var day = Math.floor(diff / 86400000);
    var hour = Math.floor(diff % 86400000 / 3600000);

    var min = Math.floor(diff % 86400000 % 3600000 / 60000);
    return {
      day, hour, min
    }
  }
};

export default dateUtil;
